package com.ag.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class FindParentUtils {
	/**
	 * 封装一个列表到树形结构的JSONArray
	 * @param list
	 * @param wrapper
	 * @return JSONArray
	 */
	public static <T> Page<JSON> findParent(org.springframework.data.domain.Page<T> sourcePage, IFindParentWrapper<T> wrapper) {
		List<T> itemList = sourcePage.getContent();
		Map<Object, T> extMap = new HashMap<>();
		
		if(CollectionUtils.isNotEmpty(itemList)) {
			wrapper.doOnce(itemList);
			
			List<Object> primarys = new ArrayList<>();
			
			for(T t : itemList) {
				Object[] idArray = wrapper.getParentIdArray(t);
				if(CollectionUtils.isNotEmpty(idArray)) {
					for(Object o : idArray) {
						if(! primarys.contains(o)) {
							primarys.add(o);
						}
					}
				}
			}
			
			
			if(CollectionUtils.isNotEmpty(primarys)) {
				List<T> l = wrapper.doFindByPrimarys(primarys);
				if(CollectionUtils.isNotEmpty(l)) {
					for(T t : l) {
						extMap.put(wrapper.getPkValue(t), t);
					}
					
				}
			}
		}
		
		return PageUtils.convert(sourcePage.map(new Function<T, JSON>() {
			@Override
			public JSON apply(T t) {
				JSONObject json = wrapper.doConvertJson(t);
				Object[] parentIdArray = wrapper.getParentIdArray(t);
				if(CollectionUtils.isNotEmpty(parentIdArray)) {
					JSONArray pJsonArray = new JSONArray();
					for(Object pO : parentIdArray) {//反过来
						T pT = extMap.get(pO);
						if(pT != null) {
							pJsonArray.add(wrapper.doConvertJson(pT));
						}
					}
					
					json.put("parent", pJsonArray);
				}
				
				return json;
			}
		}));
	}
	
	public static Integer[] commonIntIds(String tree) {
		String separator = "-";
		
		if(StringUtils.isBlank(tree)) return null;
		
		String[] split = StringUtils.split(tree, separator);
		Integer[] ret = new Integer[split.length - 1];
		for(int i = 0; i < split.length - 1; i ++) {//不要最后一个
			ret[i] = NumberUtils.parseInt(split[i]);
		}
		
		return ret;
	}
	
	public interface IFindParentWrapper<T> {
		Object[] getParentIdArray(T t);
		Object getPkValue(T t);
		List<T> doFindByPrimarys(List<Object> primarys);
		JSONObject doConvertJson(T t);
		default void doOnce(List<T> list) {} 
	}
}
